package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lwmzzz
 * @version 1.0
 * @date 2021/1/26 23:14
 * @description Lock解决线程安全
 */
public class LockDemo {
    public static void main(String[] args) {
        Demo demo = new Demo();
        new Thread(demo).start();
        new Thread(demo).start();
        new Thread(demo).start();
    }
}

class Demo implements Runnable {
    private int ticket = 100;
    private ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ": 卖票，票号为： " + ticket);
                    ticket--;
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }

    }
}
